package com.springboot.fram.core.file;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

/**
 * @author madman
 * @version 1.0
 * @date 2019/9/30 11:16
 */
public class FileUtils {

    private static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    protected static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 文件重命名
     * 生成16位得随机字符串
     *
     * @param myFileName 文件名
     * @return
     */
    public static String generateString(String myFileName) {
        // 截取图片后缀
        //String imgstr = myFileName.substring(myFileName.lastIndexOf("\\."));
        String imgstr = myFileName.substring(myFileName.lastIndexOf("."));
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 1; i <= 16; i++) {
            sb.append(allChar.charAt(random.nextInt(allChar.length())));
        }
        return sb.toString() + imgstr;
    }

    /**
     * 文件大小转换
     * 获取文件字节大小转换成 kb、M、G 等单元
     *
     * @param size
     * @return
     */
    public static String formetFileSize(long size) {
        if (size <= 0) {
            return "0B";
        }
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }


    /**
     * 文件递归读取，输入 输出
     *
     * @param args
     */
    public static void main(String[] args) {
        String dir = "D:\\work\\spring-work\\hospital_pancreatitis\\";
        String outputPath = "C:\\Users\\lihen\\Desktop\\temp.txt";
        try {
            ArrayList<String> fileNameList = readFiles(dir, new ArrayList<String>());
            System.out.println(fileNameList.size());
            for (int i = 0; i < fileNameList.size(); i++) {
                outputToTxt("\n" + fileNameList.get(i), outputPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 递归读取文件路径下的所有文件
     *
     * @param path
     * @param fileNameList
     * @return
     */
    public static ArrayList<String> readFiles(String path, ArrayList<String> fileNameList) {
        String notIgnoreFile = ".java";
        String ignoreDir = ".git,.idea,target,.mvn,logs,sql";
        File file = new File(path);
        if (file.isDirectory() && !Arrays.asList(ignoreDir).contains(file.getName())) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                // 如果是文件夹
                if (files[i].isDirectory() && !Arrays.asList(ignoreDir).contains(files[i].getName())) {
                    readFiles(files[i].getPath(), fileNameList);
                } else {
                    int lastIndexOf = files[i].getName().lastIndexOf(".");
                    //获取文件的后缀名 .jpg
                    if (lastIndexOf != -1) {
                        String suffix = files[i].getName().substring(lastIndexOf);
                        if (suffix.equals(notIgnoreFile)) {
                            String path1 = files[i].getPath();
                            fileNameList.add(readFileContent(path1));
                        }
                    }
                }
            }
        } else {
            int lastIndexOf = file.getName().lastIndexOf(".");
            if (lastIndexOf != -1) {
                //获取文件的后缀名 .jpg
                String suffix = file.getName().substring(lastIndexOf);
                if (suffix.equals(notIgnoreFile)) {
                    String path1 = file.getPath();
                    fileNameList.add(readFileContent(path1));
                }
            }
        }
        return fileNameList;
    }

    /**
     * 将内容输出到（追加）txt文件保存
     *
     * @param content
     * @throws IOException
     */
    public static void outputToTxt(String content, String outputPath) throws IOException {
        FileWriter fw = new FileWriter(outputPath, true);//追加内容
        PrintWriter pw = new PrintWriter(fw);
        pw.println(content);
        pw.close();
        fw.close();
        pw.flush();
    }

    /**
     * 读取文件内容
     *
     * @param fileName
     * @return
     */
    public static String readFileContent(String fileName) {
        String fileName2 = fileName.substring(fileName.lastIndexOf("\\") + 1);
        File file = new File(fileName);
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                sbf.append(tempStr + "\n");
            }
            reader.close();
            return "文件名：" + fileName2 + "\n" + sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return "文件名：" + fileName2 + "\n" + sbf.toString();
    }


    /**
     * 创建或重命名文件
     * ps：sss.jpg    sss(1).jpg
     *
     * @param from
     * @param toPrefix
     * @param toSuffix
     * @return
     */
    public static File createOrRenameFile(File from, String toPrefix, String toSuffix) {
        File directory = from.getParentFile();
        if (!directory.exists()) {
            if (directory.mkdir()) {
                logger.debug("Created directory " + directory.getAbsolutePath());
            }
        }
        File newFile = new File(directory, toPrefix + toSuffix);
        for (int i = 1; newFile.exists() && i < Integer.MAX_VALUE; i++) {
            newFile = new File(directory, toPrefix + "(" + i + ")" + toSuffix);
        }
        if (!from.renameTo(newFile)) {
            logger.debug("Couldn't rename file to " + newFile.getAbsolutePath());
            return from;

        }
        return newFile;
    }

    /**
     * 获取File的   . 前后字串
     *
     * @param from
     * @return
     */
    public static String[] getFileInfo(File from) {
        String fileName = from.getName();
        int index = fileName.lastIndexOf(".");
        String toPrefix = "";
        String toSuffix = "";
        if (index == -1) {
            toPrefix = fileName;
        } else {
            toPrefix = fileName.substring(0, index);
            toSuffix = fileName.substring(index, fileName.length());
        }
        return new String[]{toPrefix, toSuffix};
    }
}
